using System;
using System.Web.UI;
using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.CompositeWeb.Interfaces;
using Microsoft.Practices.CompositeWeb.Web;

namespace WCSFContrib.Samples.CustomWebClientApplications.UserControlsMasterPages
{
    /// <summary>
    /// CustomWebClientApplication that injects dependencies into
    /// UserControls and MasterPages.
    /// </summary>
    public class CustomWebClientApplication : WebClientApplication
    {
        protected override void PrePageExecute(Page page)
        {
            base.PrePageExecute(page);
            page.InitComplete += new EventHandler(OnPageInitComplete);
        }

        private void OnPageInitComplete(object sender, EventArgs e)
        {
            Page page = (Page)sender;
            page.InitComplete -= new EventHandler(OnPageInitComplete);
            ICompositionContainer moduleContainer = GetModuleContainer(new HttpContext(System.Web.HttpContext.Current));
            BuildControls(moduleContainer, page.Controls);
        }

        private void BuildControls(ICompositionContainer moduleContainer, ControlCollection controls)
        {
            foreach (Control currentControl in controls)
            {
                if (currentControl is UserControl)
                {
                    CompositionContainer.BuildItem(PageBuilder, moduleContainer.Locator, currentControl);
                    BuildControls(moduleContainer, currentControl.Controls);
                }
            }
        }
    }
}